package mq

import (
	"log"
	"pan/config"

	"github.com/streadway/amqp"
)

var (
	conn    *amqp.Connection
	channel *amqp.Channel
	err     error
)

// 如果异常关闭，会接收通知
var notifyClose chan *amqp.Error

// UpdateRabbitHost : 更新mq host
// func UpdateRabbitHost(host string) {
// 	config.RabbitURL = host
// }

// Init : 初始化MQ连接信息
func Init() {
	// 是否开启异步转移功能，开启时才初始化rabbitMQ连接
	if !config.AsyncTransferEnable {
		return
	}
	if initChannel(config.RabbitURL) {
		channel.NotifyClose(notifyClose)
	}
	// 断线自动重连
	go func() {
		for msg := range notifyClose {
			conn = nil
			channel = nil
			log.Printf("onNotifyChannelClosed: %+v\n", msg)
			initChannel(config.RabbitURL)
		}
	}()
}

func initChannel(rabbitHost string) bool {
	// 判断channel是否创建过
	if channel != nil {
		return true
	}
	// 连接rabbitmq
	conn, err = amqp.Dial(rabbitHost)
	if err != nil {
		log.Println(err.Error())
		return false
	}
	// 打开channel
	channel, err = conn.Channel()
	if err != nil {
		log.Println(err.Error())
		return false
	}
	return true
}
